var fs = require('fs')
var userPath = require('../config/pathConfig.js').userPath
var util = require('../utility/util.js')
var pageConfig = require('../config/pageConfig')
var aPageCount = pageConfig.aPageCount

var fileName = 'applyManages.data'

var safePathCheck = util.safePathCheck

module.exports = {

    insert: function(body, callback) {
        var handler = body.handler
        var introduction = body.content
        var applyDb = util.createApplyDb(handler, introduction)
        safePathCheck(userPath, fileName, function(exists) {
            if (exists) {
                var data = fs.readFileSync(userPath + fileName)
                data = JSON.parse(data)
            } else {
                var data = []
            }
            data.push(applyDb)
            data = JSON.stringify(data, null, 4)
            fs.writeFile(userPath + fileName, data, function(err) {
                if (err) {
                    console.log('applyManageHandler insert fail. err = ' + err)
                    callback('保存申请失败')
                } else {
                    callback(null, applyDb)
                }
            })


        })
    },
    find: function(filter, callback) {
        var page = filter.page
        safePathCheck(userPath, fileName, function(exists) {
            if (exists) {
                var data = fs.readFileSync(userPath + fileName)
                data = JSON.parse(data)
            } else {
                var data = []
            }
            if (page) {
                data = data.slice((page - 1) * aPageCount, page * aPageCount)
            }
            callback(null, data)
        })
    },
    findByIdAndUpdate: function(id, access, callback) {
        safePathCheck(userPath, fileName, function(exists) {
            if (!exists) {
                callback('操作失败')
            } else {
                var apply = null
                var data = fs.readFileSync(userPath + fileName)
                data = JSON.parse(data)
                data.forEach(function(item) {
                    if (item.id == id) {
                        item.status = 1
                        item.access = access
                        apply = item
                    }
                })
                data = JSON.stringify(data, null, 4)
                fs.writeFile(userPath + fileName, data, function(err) {
                    if (err) {
                        console.log('applyManageHandler findByIdAndUpdate fail. err = ' + err)
                        callback('更新数据失败')
                    } else {
                        callback(null, apply)
                    }
                })
            }
        })
    }
}